package DieSiedler;

import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class HintergrundPreload extends Thread{
	
	private Hintergrund h;
	private int normalModeSleep;
	private int fastModeSleep;
	private int sleep;
	private String[] files;
	private Image[] images;
	private int currentImage;
	private boolean active;
	
	HintergrundPreload(Hintergrund h){
		this.h = h;		
		this.files = h.getFiles();
		this.normalModeSleep = 100;
		this.fastModeSleep = 0;		
		this.images = new Image[files.length];
		normalMode();
	}
	
	public void fastMode(){
		sleep = fastModeSleep;
	}
	
	public void normalMode(){
		sleep = normalModeSleep;
	}
	
	public void run() {
		int runs = 0;
		active = true;
		for(currentImage=0; currentImage < files.length && !h.preloadComplete() && active; currentImage++){			
					
			
			images[currentImage] = loadImage();
			
			if(currentImage == 0){
				h.addImage(images[currentImage]);
			}
			
			if(sleep > 0){
				try {
					Thread.sleep(sleep);
				} catch (InterruptedException e) {
					
				}
			}
			
			// Check free Memory
			while(active && Runtime.getRuntime().freeMemory() < 800000 ){
				if(runs > 100){
					active = false;
				}
				runs ++;
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					
				}
				
				if(runs % 4 == 0){
					System.gc();
				}
			}
		}
		
		h.addImage(images);
		images = null;
		System.gc();
		
	}
		
	synchronized private Image loadImage(){
		Image img = null;
		
		// img = Toolkit.getDefaultToolkit().createImage(files[i].getPath());
		try {
			//System.out.println("Datei: "+files[currentImage]+"");
			img = ImageIO.read(getClass().getResourceAsStream(files[currentImage]));
		} catch (IOException e1) {
			active = false;
		}
		
		return img;
	}
	
	public void setActive(boolean opt){
		active = opt;
	}

}
